class SessionsController < ApplicationController
  def new
    @roles = Role.all
    render :layout => 'login'
  end
  
  def create
    @roles = Role.all
    if user = User.authenticate(params[:username], params[:password])
      session[:user_id] = user.id
      
      # redirect user home page      
      begin
        role = user.roles.find(params[:role_id])
        if role.alias == 'REPORTER'
          redirect_to url_for({:controller => 'reporter_articles'}), :notice => "Welcome "+user.username+" !"
        elsif role.alias == 'EDITOR'
          redirect_to url_for({:controller => 'editor_articles'}), :notice => "Welcome "+user.username+" !"
        elsif role.alias == 'CHAIRMAN'
          redirect_to url_for({:controller => 'chairmans'}), :notice => "Welcome "+user.username+" !"
        end
      rescue
        flash.now[:alert] = "User does not have this role" 
        render :action => 'new', :layout => 'login'
      end
      
    else 
      flash.now[:alert] = "Invalid login/password combination" 
      render :action => 'new', :layout => 'login'
    end
  end
  
  def home_login
    @roles = Role.all
    if user = User.authenticate(params[:username], params[:password])
      session[:user_id] = user.id
      
      # redirect user home page
      redirect_to url_for({:controller => 'home'}), :notice => "Welcome "+user.username+" !"
      
    else 
      flash.now[:alert] = "Invalid login/password/role combination" 
      # redirect_to url_for({:controller => 'home'})
    end
  end
  
  def destroy
    reset_session
    redirect_to "/admin", :notice => "You successfully logged out"
  end
  
  def home_logout
    reset_session
    redirect_to "/home", :notice => "You successfully logged out"
  end
  
  def reset_password
    Notifier.reset_password.deliver 
    redirect_to "/admin", :notice => "Successfully sent a message to your friend"
  end
end
